import { BlockVolume, Vector3, world } from "@minecraft/server";
import { RegionEventType } from "@sapi-game/gameEvent/events/regionEvents";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { Game, GameComponent, Region } from "@sapi-game/main";
import { Vector3Utils } from "@sapi-game/utils";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { insetVolume } from "@/parkour/func";
import { PKMapData } from "@/parkour/maps";
import { PKBuildState } from "../buildState";

export class PKMapBoundaryComponent extends GameComponent<PKBuildState> {
    override onAttach(): void {
        //防止破坏地图外方块
        const blueVolume = insetVolume(this.context.blue.volume)!;
        const redVolume = insetVolume(this.context.red.volume)!;
        this.subscribe(world.beforeEvents.playerBreakBlock, (t) => {
            if (!this.context.groupSet.findById(t.player.id)?.player) return;
            if (
                !(
                    blueVolume.isInside(t.block.location) ||
                    redVolume?.isInside(t.block.location)
                )
            ) {
                t.cancel = true;
                t.player.sendMessage("请不要破坏地图边界");
            }
        });
        //限制玩家位置
        this.restrictTeamToVolume(
            this.context.blue.team,
            blueVolume,
            this.state.blueSpawnPos!
        );
        this.restrictTeamToVolume(
            this.context.red.team,
            redVolume,
            this.state.redSpawnPos!
        );
    }

    getMapVolume(structureBase: Vector3, map: PKMapData) {
        const mapBase = Vector3Utils.add(structureBase, map.offset);
        return new BlockVolume(mapBase, Vector3Utils.add(map.volume, mapBase));
    }

    restrictTeamToVolume(
        team: PlayerGroup,
        volume: BlockVolume,
        spawnPos: Vector3
    ) {
        this.subscribe(
            Game.events.region,
            (e) => {
                if (
                    e.type == RegionEventType.Leave &&
                    team.getById(e.player.id)
                ) {
                    e.player.teleport(spawnPos);
                    e.player.sendMessage("请不要离开建造区域");
                }
            },
            new Region.CubeRegion(
                DimensionIds.Overworld,
                volume.getMin(),
                volume.getMax()
            )
        );
    }
}
